#include <iostream>
#include <vector>
using namespace std;

// 检查在给定位置放置皇后是否合法
bool isSafe(vector<vector<int>> &board, int row, int col)
{
    int i, j;
    // 检查同一列
    for (i = 0; i < row; i++)
    {
        if (board[i][col] == 1)
            return false;
    }
    // 检查左上方对角线
    for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
    {
        if (board[i][j] == 1)
            return false;
    }
    // 检查右上方对角线
    for (i = row, j = col; i >= 0 && j < board.size(); i--, j++)
    {
        if (board[i][j] == 1)
            return false;
    }
    return true;
}

// 解决N皇后问题的递归函数
bool solveNQueensUtil(vector<vector<int>> &board, int row)
{
    if (row == board.size())
    {
        return true;
    }
    for (int col = 0; col < board.size(); col++)
    {
        if (isSafe(board, row, col))
        {
            board[row][col] = 1;
            if (solveNQueensUtil(board, row + 1))
                return true;
            board[row][col] = 0;
        }
    }
    return false;
}

// 解决4皇后问题并输出结果
void solve4Queens()
{
    vector<vector<int>> board(4, vector<int>(4, 0));
    if (solveNQueensUtil(board, 0))
    {
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                cout << board[i][j] << " ";
            }
            cout << endl;
        }
    }
    else
    {
        cout << "Solution does not exist" << endl;
    }
}

int main()
{
    solve4Queens();
    return 0;
}
